package com.leyou.filter;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.FilterProperties;
import com.leyou.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties properties;

    @Autowired
    private FilterProperties filterProperties;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        // 初始化zuul的上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        // 从上下文对象中获取request
        HttpServletRequest request = context.getRequest();
        
        // 获取当前请求的路径
        StringBuffer url = request.getRequestURL();

        for (String path : this.filterProperties.getAllowPaths()) {
            if (StringUtils.contains(url, path)){
                return false;
            }
        }
        
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 初始化zuul的上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        // 从上下文对象中获取request
        HttpServletRequest request = context.getRequest();

        // 获取jwt
        String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());

        try {
            // 解析jwt
            JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            // 设置响应状态码
            context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            // 不转发请求，拦截请求
            context.setSendZuulResponse(false);
        }

        return null;
    }
}
